package com.yuhj.cateyemovie.activitys;

import java.util.ArrayList;
import java.util.StringTokenizer;

import com.yuhj.cateyemovie.R;
import com.yuhj.cateyemovie.R.layout;
import com.yuhj.cateyemovie.R.menu;
import com.yuhj.cateyemovie.adapter.HotCommentAdapter;
import com.yuhj.cateyemovie.adapter.ShortCommentAdapter;
import com.yuhj.cateyemovie.bean.Comments;
import com.yuhj.cateyemovie.bean.MovieDetail;
import com.yuhj.cateyemovie.clients.ClientApi;
import com.yuhj.cateyemovie.interfaces.MovieDetailCallback;
import com.yuhj.cateyemovie.interfaces.ShortsCommentsCallback;
import com.yuhj.cateyemovie.utils.BitMapUtils;
import com.yuhj.cateyemovie.utils.FastBlur;
import com.yuhj.cateyemovie.utils.ImageCache;
import com.yuhj.cateyemovie.utils.LoadingAinm;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v4.util.LruCache;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.SearchManager.OnCancelListener;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @name MovieDetailActivity
 * @Descripation 电影详情界面<br>
 * @author 禹慧军
 * @date 2014-11-3
 * @version 1.0
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@SuppressLint("NewApi")
public class MovieDetailActivity extends Activity implements
		android.view.View.OnClickListener {
	private TextView txtwishSee;
	private TextView txtRat;
	private RelativeLayout wishLikeLayout;
	private LinearLayout pingfenLayout;
	private long movie_id = 78911;
	private TextView txtname;
	private TextView txtRatNum, txtCategory, txtfilmTime, txtTime, txtCountry;
	private Button btn_buy;
	private TextView txtDirector, txtStar, txtSummary;
	private ImageView image_tag;
	private ImageView movie_star1, movie_star2, movie_star3, movie_star4,
			movie_star5;
	private LruCache<String, Bitmap> lruCache;
	private Button btn_seeImage;
	private ImageView movie_image, img_summary;
	private String summaryComplete;
	private String summartShort;
	private RelativeLayout relativeLayoutimg_movie_bg;
	private ListView shortListView;
	private ListView hotListView;
	private boolean sumflag = false;
	private String title;
	private HotCommentAdapter hotCommentAdapter;
	private ShortCommentAdapter shortCommentAdapter;
	private ImageView movieInformation1, movieInformation2, movieInformation3,
			movieInformation4;
	private ScrollView dataLiScrollView;
	private RelativeLayout loadRelativeLayout;
	private LinearLayout btn_imageLayout;
	private String Url = "http://api.mobile.meituan.com/dianying/v2/movie/"
			+ movie_id
			+ ".json?token=&utm_campaign=AmovieBmovieC110189035512576D-1&movieBundleVersion=100&utm_source=wandoujia&utm_medium=android&utm_term=100&utm_content=352706060172190&ci=1&uuid=A1A230538BAA987DFF805E95D3B8D53EAB6025EC580F2C6C56CF303DD5BB5A2E";
	private String shortCommentUrl = "http://api.mobile.meituan.com/dianying/comments/movie/"
			+ movie_id + ".json?token=&offset=0&limit=15";
	private String hotCommentUrl = "http://api.mobile.meituan.com/dianying/sns/0/"
			+ movie_id + "/hotTopics.json";
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg == null) {
				loadRelativeLayout.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(), "网络异常，请检查！", 1).show();
			} else {
				loadRelativeLayout.setVisibility(View.GONE);
				dataLiScrollView.setVisibility(View.VISIBLE);
				final MovieDetail movieDetail = (MovieDetail) msg.obj;
				txtname.setText(movieDetail.getName());
				title= movieDetail.getName();
				txtRatNum.setText("（" + movieDetail.getsNum() + "人评分）");
				txtCategory.setText("类型：" + movieDetail.getCat());
				txtCountry.setText("地区：" + movieDetail.getCountry());
				txtfilmTime
						.setText("片长：" + movieDetail.getHowlongtime() + "分钟");
				txtTime.setText("上映：" + movieDetail.getTime());
				txtDirector.setText("导演：" + movieDetail.getDirector() + "\n"
						+ "演员：" + movieDetail.getStar());
				summaryComplete = "剧情：" + movieDetail.getSummarry();
				summartShort = summaryComplete.substring(0, 90) + "...";
				txtSummary.setText(summartShort);
				String Classification = movieDetail.getVer();
				if (Classification.contains("IMAX 3D")) {
					image_tag.setImageResource(R.drawable.ic_3d_imax);
				} else if (Classification.contains("2D")) {
					image_tag.setImageResource(R.drawable.ic_2d_imax);
				} else if (Classification.contains("3D")) {
					image_tag.setImageResource(R.drawable.ic_3d);
				}
				float pingfen = movieDetail.getLevel();
				if (pingfen > 2) {
					if (pingfen > 4) {
						if (pingfen > 6) {
							if (pingfen > 8) {
								if (pingfen > 9) {
									movie_star1
											.setImageResource(R.drawable.star_med_on);
									movie_star2
											.setImageResource(R.drawable.star_med_on);
									movie_star3
											.setImageResource(R.drawable.star_med_on);
									movie_star4
											.setImageResource(R.drawable.star_med_on);
									movie_star5
											.setImageResource(R.drawable.star_med_on);

								} else {
									movie_star1
											.setImageResource(R.drawable.star_med_on);
									movie_star2
											.setImageResource(R.drawable.star_med_on);
									movie_star3
											.setImageResource(R.drawable.star_med_on);
									movie_star4
											.setImageResource(R.drawable.star_med_on);
								}
							} else {
								movie_star1
										.setImageResource(R.drawable.star_med_on);
								movie_star2
										.setImageResource(R.drawable.star_med_on);
								movie_star3
										.setImageResource(R.drawable.star_med_on);
							}
						} else {
							movie_star1
									.setImageResource(R.drawable.star_med_on);
							movie_star2
									.setImageResource(R.drawable.star_med_on);
						}
					} else {
						movie_star1.setImageResource(R.drawable.star_med_on);
					}
				}
				new ImageCache(getApplicationContext(), lruCache, movie_image,
						movieDetail.getImg(), "CatEyeMovie", 120, 200);
				new MyTask().execute(movieDetail.getImg());
				movieInformation1
						.setImageResource(R.drawable.bg_default_cat_gray);
				movieInformation2
						.setImageResource(R.drawable.bg_default_cat_gray);
				movieInformation3
						.setImageResource(R.drawable.bg_default_cat_gray);
				movieInformation4
						.setImageResource(R.drawable.bg_default_cat_gray);
				new ImageCache(getApplicationContext(), lruCache,
						movieInformation1, movieDetail.getImages()[0],
						"CatEyeMovie", 120, 120);
				new ImageCache(getApplicationContext(), lruCache,
						movieInformation2, movieDetail.getImages()[1],
						"CatEyeMovie", 120, 120);
				new ImageCache(getApplicationContext(), lruCache,
						movieInformation3, movieDetail.getImages()[2],
						"CatEyeMovie", 120, 120);
				new ImageCache(getApplicationContext(), lruCache,
						movieInformation4, movieDetail.getImages()[3],
						"CatEyeMovie", 120, 120);
				btn_seeImage.setText(movieDetail.getPicCount() + "");
			}
		};
	};

	private Handler shortCommenthandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg == null) {

			} else {
				shortCommentAdapter.bindData((ArrayList<Comments>) msg.obj);
				shortListView.setAdapter(shortCommentAdapter);
				shortCommentAdapter.notifyDataSetChanged();
			}
		};
	};

	private Handler hotCommenthandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg == null) {

			} else {
				hotCommentAdapter.bindData((ArrayList<Comments>) msg.obj);
				hotListView.setAdapter(hotCommentAdapter);
				hotCommentAdapter.notifyDataSetChanged();
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_playing_detail);
		lruCache = ImageCache.GetLruCache(getApplicationContext());
		initView();
		LoadingAinm.ininLoding(MovieDetailActivity.this);
		shortCommentAdapter = new ShortCommentAdapter(getApplicationContext());
		hotCommentAdapter = new HotCommentAdapter(getApplicationContext());
		new Thread(new Runnable() {

			@Override
			public void run() {
				ClientApi.getMovieDetail(Url, new MovieDetailCallback() {

					@Override
					public void getresult(MovieDetail result) {
						Message msg = Message.obtain();
						msg.obj = result;
						handler.sendMessage(msg);
					}
				});

			}
		}).start();

	    new Thread(new downShortCommet()).start();
		new Thread(new downHotCommet()).start();
	}

	private void initView() {
		txtRat = (TextView) findViewById(R.id.txt_pingfen);
		btn_seeImage = (Button) findViewById(R.id.btn_SeeImage);
		btn_seeImage.setOnClickListener(this);
		txtwishSee = (TextView) findViewById(R.id.txt_want_like);
		txtRat.setOnClickListener(this);
		txtwishSee.setOnClickListener(this);
		wishLikeLayout = (RelativeLayout) findViewById(R.id.layout_want_like);
		pingfenLayout = (LinearLayout) findViewById(R.id.layout_pingfen);
		txtRatNum = (TextView) findViewById(R.id.txt_pingfen_count);
		txtname = (TextView) findViewById(R.id.movie_name);
		txtCategory = (TextView) findViewById(R.id.txt_leixing);
		txtCountry = (TextView) findViewById(R.id.txt_address);
		txtDirector = (TextView) findViewById(R.id.movie_actor);
		txtSummary = (TextView) findViewById(R.id.movie_summary);
		txtSummary.setOnClickListener(this);
		txtTime = (TextView) findViewById(R.id.txt_palyTime);
		txtfilmTime = (TextView) findViewById(R.id.txt_timelong);
		image_tag = (ImageView) findViewById(R.id.img_movie_leixing);
		movie_star1 = (ImageView) findViewById(R.id.movie_star1);
		movie_star2 = (ImageView) findViewById(R.id.movie_star2);
		movie_star3 = (ImageView) findViewById(R.id.movie_star3);
		movie_star4 = (ImageView) findViewById(R.id.movie_star4);
		movie_star5 = (ImageView) findViewById(R.id.movie_star5);
		movie_image = (ImageView) findViewById(R.id.img_movie_su);
		relativeLayoutimg_movie_bg = (RelativeLayout) findViewById(R.id.img_movie_bg);

		movieInformation1 = (ImageView) findViewById(R.id.movie_information_image1);
		movieInformation2 = (ImageView) findViewById(R.id.movie_information_image2);
		movieInformation3 = (ImageView) findViewById(R.id.movie_information_image3);
		movieInformation4 = (ImageView) findViewById(R.id.movie_information_image4);
		movieInformation1.setOnClickListener(this);
		movieInformation2.setOnClickListener(this);
		movieInformation3.setOnClickListener(this);
		movieInformation4.setOnClickListener(this);
		img_summary = (ImageView) findViewById(R.id.img_summary);
		shortListView = (ListView) findViewById(R.id.duanpin_customListView);
		hotListView = (ListView) findViewById(R.id.shequ_customListView);
		loadRelativeLayout=(RelativeLayout) findViewById(R.id.lodingRelativeLayout);
		dataLiScrollView= (ScrollView) findViewById(R.id.data);
		btn_imageLayout=(LinearLayout) findViewById(R.id.btn_image);
		btn_imageLayout.setOnClickListener(this);
	}
	/**
	 * 柔化效果(高斯模糊)
	 * 
	 * @param bmp
	 * @return
	 */
	private void blur(Bitmap bkg, View view) {
		float scaleFactor = 1;
		float radius = 20;
		Bitmap overlay = Bitmap.createBitmap(
				(int) (view.getMeasuredWidth() / 2),
				(int) (view.getMeasuredHeight() / scaleFactor),
				Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(overlay);
		canvas.translate(-view.getLeft() / scaleFactor, -view.getTop()
				/ scaleFactor);
		canvas.scale(1 / scaleFactor, 1 / scaleFactor);
		Paint paint = new Paint();
		paint.setFlags(Paint.FILTER_BITMAP_FLAG);
		canvas.drawBitmap(bkg, 0, 0, paint);
		overlay = FastBlur.doBlur(overlay, (int) radius, true);
		view.setBackground(new BitmapDrawable(getResources(), overlay));
	}

	@Override
	public void onClick(View v) {
		if (v == txtRat) {
			pingfenLayout.setVisibility(View.VISIBLE);
			wishLikeLayout.setVisibility(View.GONE);
		} else if (v == txtwishSee) {
			wishLikeLayout.setVisibility(View.VISIBLE);
			pingfenLayout.setVisibility(View.GONE);

		} else if (v == txtSummary) {
			if (!sumflag) {
				txtSummary.setText(summaryComplete);
				sumflag = true;
				img_summary.setImageResource(R.drawable.ic_arrow_up_gray);
			} else {
				txtSummary.setText(summartShort);
				sumflag = false;
				img_summary.setImageResource(R.drawable.ic_arrow_down_gray);
			}
		}else if (v==btn_seeImage) {
			//Toast.makeText(getApplicationContext(), "dianji", 1).show();
			Intent intent =new Intent(MovieDetailActivity.this,ImageGridActivity.class);
			intent.putExtra("title",title );
			intent.putExtra("id",movie_id+"");
			startActivity(intent);
		}else if (v==movieInformation1) {
			Intent intent =new Intent(MovieDetailActivity.this,ImageViewPagerActivity.class);
			intent.putExtra("position", 1);
			intent.putExtra("id",movie_id+"");
			startActivity(intent);
		}else if (v==movieInformation2) {
			Intent intent =new Intent(MovieDetailActivity.this,ImageViewPagerActivity.class);
			intent.putExtra("position", 2);
			intent.putExtra("id",movie_id+"");
			startActivity(intent);
		}else if (v==movieInformation3) {
			Intent intent =new Intent(MovieDetailActivity.this,ImageViewPagerActivity.class);
			intent.putExtra("position", 3);
			intent.putExtra("id",movie_id+"");
			startActivity(intent);
		}else if (v==movieInformation4) {
			Intent intent =new Intent(MovieDetailActivity.this,ImageViewPagerActivity.class);
			intent.putExtra("position",4);
			intent.putExtra("id",movie_id+"");
			startActivity(intent);
		}
		

	}

	class MyTask extends AsyncTask<String, Void, byte[]> {

		@Override
		protected byte[] doInBackground(String... params) {
			// TODO Auto-generated method stub
			return BitMapUtils.downLoadImage(params[0]);
		}

		@SuppressLint("NewApi")
		@Override
		protected void onPostExecute(byte[] result) {
			if (result != null) {
				Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0,
						result.length);
				// Bitmap bitmap =BitmapFactory.decodeResource(getResources(),
				// R.drawable.b);
				blur(bitmap, relativeLayoutimg_movie_bg);
			}
			super.onPostExecute(result);
		}

	}

	class downShortCommet implements Runnable {

		@Override
		public void run() {

			ClientApi
					.getShortComment(
							"http://api.mobile.meituan.com/dianying/comments/movie/78911.json?token=&offset=0&limit=15",
							new ShortsCommentsCallback() {

								@Override
								public void getresult(ArrayList<Comments> result) {
									Message msg = Message.obtain();
									msg.obj = result;
									shortCommenthandler.sendMessage(msg);
								}
							});
		}

	}

	class downHotCommet implements Runnable {

		@Override
		public void run() {

			ClientApi.getHotComment(hotCommentUrl,
					new ShortsCommentsCallback() {

						@Override
						public void getresult(ArrayList<Comments> result) {
							Message msg = Message.obtain();
							msg.obj = result;
							hotCommenthandler.sendMessage(msg);
						}
					});
		}

	}

}
